package com.sqly.doc.menu.fjh;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.view.menu.MenuPopupHelper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.support.v7.widget.PopupMenu;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sqly.doc.R;
import com.sqly.doc.adapter.CommonAdapter;
import com.sqly.doc.adapter.ViewHolder;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.menu.camera.CameraChoose;
import com.sqly.doc.pojo.FjhDycrhsf;
import com.sqly.doc.pojo.FjhSf;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.util.DateConvert;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.view.StringUtils;
import com.sqly.doc.view.XListView;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * 肺结核患者随访记录列表
 * Created by Administrator on 2017/11/28 0028.
 */

public class fjh_list extends MyBaseActivity{


    XListView listView;
    //标题
    TextView title, uname;
    LinearLayout back;
    ZLoadingDialog dialog;//加载动画
    Context con = fjh_list.this;
    private int pageNum1 = 1;// 无关键字页数
    List<FjhDycrhsf> fjhDycrhsflist;//产后访视
    List<FjhSf> fjhSflist;//第一次产后访视

    String type = "";//类型
    String url = "";//请求的路径
    private EditText key;

    @Override
    protected void initUI() {
        setContentView(R.layout.fjh2_list);
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        type = getIntent().getStringExtra("type");
        if (type.equals("第1次入户随访记录"))
            url = HttpUrl.GetFjhDycrhsfList;
        if (type.equals("肺结核患者随访服务记录"))
            url = HttpUrl.GetFjhsfList;

        title.setText(type);
        key=(EditText)findViewById(R.id.key);
        key.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                getJumin();
            }
        });
        uname.setText("新增");
        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type.equals("第1次入户随访记录"))
                    startActivity(new Intent(con, fjhdycrhsf.class).putExtra("type", "add"));
                if (type.equals("肺结核患者随访服务记录"))
                    startActivity(new Intent(con, fjhsf.class).putExtra("type", "add"));
            }
        });
        back = (LinearLayout) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        listView = (XListView) findViewById(R.id.listView);
        listView.setPullLoadEnable(true);
        dialog = new ZLoadingDialog(con);
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.parseColor("#1C86EE"))//颜色
                .setHintText("Loading...")
                .setHintTextSize(16) // 设置字体大小 dp
                .setHintTextColor(Color.parseColor("#1C86EE"));  // 设置字体颜色
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
                //showPopupMenu(view, i);
                toEditView(i);
            }
        });
    }

    private void toEditView(final int position){
        Bundle b = new Bundle();
        if (type.equals("第1次入户随访记录")) {
            b.putSerializable("b", fjhDycrhsflist.get(position - 1));
            startActivity(new Intent(con, fjhdycrhsf.class).putExtras(b).putExtra("type", "edit"));
        }else if (type.equals("肺结核患者随访服务记录")) {
            b.putSerializable("b", fjhSflist.get(position - 1));
            startActivity(new Intent(con, fjhsf.class).putExtras(b).putExtra("type", "edit"));
        }
    }

    private void toPaiZhaoView(final int position){
        Bundle b = new Bundle();
        if (type.equals("第1次入户随访记录")) {
            FjhDycrhsf itemInList = fjhDycrhsflist.get(position - 1);
            startActivity(new Intent(con, CameraChoose.class)
                    .putExtra("type", "edit")
                    .putExtra("jkdah", itemInList.getJKDAH())
                    .putExtra("tabId", itemInList.getSFJLH())
                    .putExtra("tabType", "fjhDycrhsf")
            );
        }else if (type.equals("肺结核患者随访服务记录")) {
            FjhSf itemInList = fjhSflist.get(position - 1);
            startActivity(new Intent(con, CameraChoose.class)
                    .putExtra("type", "edit")
                    .putExtra("cardnum", itemInList.getCARDNUM())
                    .putExtra("tabId", itemInList.getSFJLH())
                    .putExtra("tabType", "fjhSf")
            );
        }
    }

    PopupMenu popupMenu;
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @SuppressLint("RestrictedApi")
    private void showPopupMenu(View view, final int position ) {
        // View当前PopupMenu显示的相对View的位置
        popupMenu = new PopupMenu(fjh_list.this, view, Gravity.END);
        // menu布局
        popupMenu.getMenuInflater().inflate(R.menu.list_menu, popupMenu.getMenu());
        // menu的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
//                if(item.getItemId() == R.id.item_edit){
//                    toEditView(position);
//                }else if(item.getItemId() == R.id.item_pz){
//                    toPaiZhaoView(position);
//                }
                return false;
            }
        });

        // PopupMenu关闭事件
        popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu menu) {
                //Toast.makeText(getApplicationContext(), "关闭PopupMenu", Toast.LENGTH_SHORT).show();
            }
        });
        //使用反射，强制显示菜单图标
        try {
            Field field = popupMenu.getClass().getDeclaredField("mPopup");
            field.setAccessible(true);
            MenuPopupHelper mHelper = (MenuPopupHelper) field.get(popupMenu);
            mHelper.setForceShowIcon(true);
        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        popupMenu.show();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (NetWorkUtils.isNetworkConnected(con)) {//联网状态
            getJumin();
        }
    }

    @Override
    protected void initListener() {

    }

    public void getJumin() {
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("page", pageNum1 + "");
        if(!StringUtils.isEmpty(key.getText().toString()))
            ps.add("XINGMING",key.getText().toString());
      /*  ps.add("XINGMING",SharedPreferencesUtils.getParam(con,"uname","").toString());*/
        UserClient.get(url, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                MyToastUtil.ShowToast(con, "请求失败");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                dialog.dismiss();
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {

                    if (type.equals("第1次入户随访记录")) {
                        List<FjhDycrhsf> ll = JSON.parseArray(ret.getList(), FjhDycrhsf.class);
                        if (pageNum1 == 1) {
                            fjhDycrhsflist = new ArrayList<FjhDycrhsf>();
                        }
                        for (int i = 0; i < ll.size(); i++) {

                            fjhDycrhsflist.add(ll.get(i));
                        }
                        listView.stopRefresh();
                        listView.stopLoadMore();
                        listView.setRefreshTime("刚刚");
                        listView.setXListViewListener(new XListView.IXListViewListener() {
                            @Override
                            public void onRefresh() {
                                pageNum1 = 1;
                                getJumin();
                            }

                            @Override
                            public void onLoadMore() {
                                pageNum1 = pageNum1 + 1;
                                getJumin();
                            }
                        });
                        listView.setAdapter(new CommonAdapter<FjhDycrhsf>(con, fjhDycrhsflist, R.layout.ycf_chfsjl_item) {
                            @Override
                            public void convert(ViewHolder helper, FjhDycrhsf item) {
                                helper.setText(R.id.xm, item.getXINGMING());
                                helper.setText(R.id.jkdah, "健康档案号:" + item.getJKDAH());
                                helper.setText(R.id.sfrq,  DateConvert.dateToString(DateConvert.toDate(item.getSFRQ(), DateConvert.YMD), DateConvert.YMD)+"    ");
                            }
                        });
                        listView.setSelection(fjhDycrhsflist.size() - ll.size());
                    }


                    if (type.equals("肺结核患者随访服务记录")) {
                        List<FjhSf> ll = JSON.parseArray(ret.getList(), FjhSf.class);
                        if (pageNum1 == 1) {
                            fjhSflist = new ArrayList<FjhSf>();
                        }
                        for (int i = 0; i < ll.size(); i++) {

                            fjhSflist.add(ll.get(i));
                        }
                        listView.stopRefresh();
                        listView.stopLoadMore();
                        listView.setRefreshTime("刚刚");
                        listView.setXListViewListener(new XListView.IXListViewListener() {
                            @Override
                            public void onRefresh() {
                                pageNum1 = 1;
                                getJumin();
                            }

                            @Override
                            public void onLoadMore() {
                                pageNum1 = pageNum1 + 1;
                                getJumin();
                            }
                        });
                        listView.setAdapter(new CommonAdapter<FjhSf>(con, fjhSflist, R.layout.ycf_chfsjl_item) {
                            @Override
                            public void convert(ViewHolder helper, FjhSf item) {
                                helper.setText(R.id.xm, item.getXINGMING());
                                helper.setText(R.id.jkdah, "健康档案号:" + item.getJKDAH());
                                helper.setText(R.id.sfrq, DateConvert.dateToString(DateConvert.toDate(item.getSFRQ(), DateConvert.YMD), DateConvert.YMD)+"    ");
                            }
                        });
                        listView.setSelection(fjhSflist.size() - ll.size());
                    }
                }
            }
        });
    }
}
